# -*- coding: UTF-8 -*-
import kivy
from ui.hat_widget import HatWidget
from model import gamestate
from model.json_loader import JsonLoader
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
import urllib2
from constants import HOST

class ErrorPopup(Popup):
    pass

class Join(HatWidget):
    def __init__(self, gamestate, presenter, **kwargs):
        self.gamestate = gamestate
        self.presenter = presenter
        super(Join, self).__init__(**kwargs)
        self.error_popup = ErrorPopup()
        if self.gamestate.current_added_player is not None:
            player_json = {
                u'name': self.gamestate.current_added_player.name,
                u'words': [],
                u'id': gamestate.remote_id,
                u'pin': gamestate.pin_code
            }
            for word in gamestate.current_added_player.words:
                player_json[u'words'].append(word.text)
            loader = JsonLoader()
            try:
                loader.dump_to_url('{}/add_player_from_json'.format(HOST)
                                   ,player_json)
            except urllib2.HTTPError as e:
                if e.code == 409:
                    self.error_popup.title = _('User name already used')
                    self.error_popup.open()
            self.gamestate.current_added_player = None
        self.open_numpad = False

    def go_back(self):
        self.gamestate.is_joining = False
        self.presenter.change_phase(gamestate.Phase.WELCOME)

    def go_next(self):
        loader = JsonLoader()
        try:
            data = loader.load_from_url(HOST+'/game_template_json?game_id='+
                                        self.game_id.text +
                                        '&pin=' + self.pin_code.text)
            self.gamestate.remote_id = int(self.game_id.text)
            self.gamestate.pin_code = int(self.pin_code.text)
            self.gamestate.is_joining = True
            self.gamestate.settings = gamestate.Settings()
            self.gamestate.settings.words_number = data[u'settings']\
                                                      [u'word_count']
            self.gamestate.players = gamestate.Players([])
            self.presenter.change_phase(gamestate.Phase.ADD_PLAYER)
        except urllib2.HTTPError as msg:
            if msg.code == 404:
                error_text = _('Game not found.\nCheck your game-id')
            elif msg.code == 403:
                error_text = _('Incorrect pin.')
            else:
                error_text = _('Network error')
            self.error_popup.title = error_text
            self.error_popup.open()

    def check_id(self):
        self.is_correct_id = self.game_id.text.isdigit()
        self.next_button.enabled = (self.is_correct_id and
                                    self.is_correct_pin)

    def check_pin(self):
        self.is_correct_pin = (self.pin_code.text.isdigit() and \
                               len(self.pin_code.text) == 4)
        self.next_button.enabled = (self.is_correct_id and self.is_correct_pin)

